package com.filetest.controller;

import com.filetest.model.FileDownDTO;
import com.filetest.model.FileMetadata;
import com.filetest.service.FileService;
import com.filetest.service.PathUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author xhw
 */
@RestController
@RequestMapping("/file")
public class FileController {

    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    // 上传文件
    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") Integer userId,
            @RequestParam("logicPath") String logicPath
    ) {
        try {
            String normalizedPath = PathUtils.normalizePath(logicPath);
            fileService.saveFile(file, userId, normalizedPath);
            return ResponseEntity.ok(Map.of("message", "File uploaded successfully", "logicPath", normalizedPath));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("message", e.getMessage()));
        }
    }

    // 查询逻辑路径下的目录以及文件列表
    @GetMapping("/{userId}/children/**")
    public ResponseEntity<?> listFiles(
            HttpServletRequest request,
            @PathVariable Integer userId
    ) {
        try {
            String logicPath = extractLogicPath(request, "/file/" + userId + "/children/");
            String normalizedPath = PathUtils.normalizePath(logicPath);
            List<FileMetadata> files = fileService.listChildren(userId, normalizedPath);
            return ResponseEntity.ok(files);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("message", "获取失败", "error", e.getMessage()));
        }
    }

    // 查询指定文件的元数据并提供下载链接
    @GetMapping("/{userId}/**")
    public ResponseEntity<?> getFileDetail(
            HttpServletRequest request,
            @PathVariable Integer userId
    ) {
        try {
            String logicPath = extractLogicPath(request, "/file/" + userId + "/");
            String normalizedPath = PathUtils.normalizePath(logicPath);
            FileMetadata fileMetadata = fileService.getFileDetails(userId, normalizedPath);
            if (fileMetadata == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("message", "没有找到文件"));
            }

            FileDownDTO fileDownDTO = new FileDownDTO();
            fileDownDTO.setFileMetadata(fileMetadata);

            if (fileMetadata.getType() != null && !fileMetadata.getType().trim().isEmpty()) {
                String downloadUrl = fileService.createDownloadUrl(userId, normalizedPath);
                fileDownDTO.setDownloadUrl(downloadUrl);
            }

            return ResponseEntity.ok(fileDownDTO);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("message", "没有找到文件", "error", e.getMessage()));
        }
    }

    // 删除指定文件或目录
    @DeleteMapping("/{userId}/**")
    public ResponseEntity<?> deleteFile(
            HttpServletRequest request,
            @PathVariable Integer userId
    ) {
        try {
            String logicPath = extractLogicPath(request, "/file/" + userId + "/children/");
            String normalizedPath = PathUtils.normalizePath(logicPath);
            fileService.deleteFile(userId, normalizedPath);
            return ResponseEntity.ok(Map.of("message", "File deleted successfully"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("message", "Error deleting file", "error", e.getMessage()));
        }
    }

    // 下载文件
    @GetMapping("/download/{userId}/**")
    public ResponseEntity<?> downloadFile(
            HttpServletRequest request,
            @PathVariable Integer userId
    ) {
        try {
            String requestURI = URLDecoder.decode(request.getRequestURI(), StandardCharsets.UTF_8);
            String data = "/file/download/" + userId + "/";
            String logicPath = requestURI.substring(request.getContextPath().length() + data.length());
            String normalizedPath = PathUtils.normalizePath(logicPath);

            FileSystemResource file = fileService.getFileSystemResource(userId, normalizedPath);
            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(Map.of("message", "文件未找到"));
            }

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getFilename());

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(file);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Map.of("message", "路径解析失败", "error", e.getMessage()));
        }
    }


    private String extractLogicPath(HttpServletRequest request, String prefix) {
        String requestURI = URLDecoder.decode(request.getRequestURI(), StandardCharsets.UTF_8);
        String logicPath = requestURI.substring(requestURI.indexOf(prefix) + prefix.length());
        return logicPath;
    }

    private String extractFullPath(HttpServletRequest request) {
        return URLDecoder.decode(request.getRequestURI(), StandardCharsets.UTF_8);
    }
}